<template>
  <div>
    <!-- 抽离面包屑 -->
    <crumbs secondTitle="权限管理" thirdTitle="角色列表"></crumbs>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialog = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="delTag(scope.row, item1.id)">
                  {{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级/三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index) in item1.children"
                  :key="item2.id"
                  :class="[index === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 渲染二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delTag(scope.row, item2.id)"
                    >
                      {{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, index) in item2.children"
                      :key="index.id"
                      closable
                      @close="delTag(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="rolesEdit(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="rolesPop(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allotSwitch"
      width="50%"
      @close="rolesClose"
    >
      <!-- 树形组件 -->
      <!-- default-expand-all 默认展开所有节点 -->
      <el-tree
        :data="rightList"
        :props="rolesProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        :default-checked-keys="promissList"
        default-expand-all
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotSwitch = false">取 消</el-button>
        <el-button type="primary" @click="addUserPromiss">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <!--点击编辑的对话框  -->
    <role-dialog
      :addRolesDialog.sync="addRolesDialog"
      :RolesruleForm="RolesruleForm"
    />
  </div>
</template>

<script>
import roleDialog from './roleDialog'
import {
  getUserList,
  delUserPermiss,
  getAllPermiss,
  getUserPermiss,
  idRights,
  delRights
} from '@/api/roles'
export default {
  components: {
    roleDialog
  },
  data() {
    return {
      rolesList: [],
      // 控制分配的显示的对话框的显示与隐藏
      allotSwitch: false,
      // 所有权限的数据
      rightList: [],
      // 树形控件规则
      rolesProps: {
        children: 'children',
        label: 'authName'
      },
      // 所有三级 id 的集合
      promissList: [],
      // 分配角色的 id
      roleId: [],
      // 添加
      addRolesDialog: false,
      RolesruleForm: {
        roleId: '', // 角色 ID 必填
        roleName: '', // 角色名称 不能为空
        roleDesc: '' // 角色描述
      },
      // 编辑
      editRolesDialog: false
    }
  },
  methods: {
    // 根据id查询角色
    async rolesEdit(id) {
      this.editRolesDialog = true
      const res = await idRights(id)
      if (res.meta.status === 200) {
        // 把数据传入到编辑表单里
        this.RolesruleForm = res.data
      } else {
        this.$message.error('获得角色数据失败')
      }
      this.addRolesDialog = true
    },
    // 删除角色
    async deleteRoles(id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await delRights(id)
        if (res.meta.status === 200) {
          // 重新渲染
          this.loadUserList()
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        this.$message.info('取消删除')
      }
    },

    // 角色授权
    async addUserPromiss() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const res = await getUserPermiss(this.roleId, keysStr)
      if (res.meta.status === 200) {
        this.$message.success('更新成功')
        this.loadUserList()
        this.allotSwitch = false
      }
    },
    // 关闭弹出框 清空 promissList 数组
    rolesClose() {
      this.promissList = []
    },
    // 通过递归 获取角色下 所有三级权限的id 保存到 promissList 中
    // 在 分配权限 rolesPop() 事件中执行
    getPromissList(node, arr) {
      // 如果当前 node 节点不包括 children 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getPromissList(item, arr))
    },
    async rolesPop(role) {
      // 把 role.id 存储 到数组中
      this.roleId = role.id
      // 获取所有权限信息
      const res = await getAllPermiss()
      if (res.meta.status !== 200) {
        this.$message.success('获取权限列表失败')
      }
      this.rightList = res.data
      this.getPromissList(role, this.promissList)
      // this.promissList = []
      this.allotSwitch = true
    },
    // 删除角色指定权限
    async delTag(roleID, rightID) {
      try {
        await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示')
        const res = await delUserPermiss(roleID, rightID)
        if (res.meta.status === 200) {
          this.$message.success('取消权限成功')
          // 防止列表刷新 把 roleID 的值 赋给 res.data
          roleID.children = res.data
        }
        if (res.meta.status !== 200) {
          return this.$message.error('取消权限失败')
        }
      } catch (error) {
        return this.$message.info('已取消删除')
      }
    },
    async loadUserList() {
      const res = await getUserList()
      if (res.meta.status !== 200) {
        return this.$message.error('创建失败')
      }
      this.rolesList = res.data
    }
  },
  mounted() {
    this.loadUserList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
